# -*- coding: utf-8 -*-

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,time
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "太平退糖鼓糖尿病并发症保险"
    # 生产产品数据
    def genProductInfo(self):

        plan = {
            "planA":{
                # 年龄段
                "year":[str(i) for i in range(30,51)],
                #性别
                "gender":["M","F"],
                #保额
                "money":["50000","100000","150000"],
                # 保障期限
                "expire":["1年"],
                #缴费类型
                "payType":["年缴"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(51,61 )],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000"],
                # 保障期限
                "expire": ["1年"],
                # 缴费类型
                "payType": ["年缴"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(61, 66)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000"],
                # 保障期限
                "expire": ["1年"],
                # 缴费类型
                "payType": ["年缴"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["expire"],plan[k]["payType"]):
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(

                    v[0],v[1],v[2],v[3],v[4]
                ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(

                    v[0],v[1],v[2],v[3],v[4]
                ))

    #执行爬虫
    def requestJson(self,dt=None):

        data = {
            "pageName": "productAdd",
            "goods_id": "60507",
            "merchant_id": "B2C",
            "toubaoli_money":"",
            "productCode": "33333",
            "productId": "241ebfff - 519f - 4b43 - a81a - 9c0bc1e958bf",
            "riskCode": "3333300001",
            "productName": "糖尿病并发症保险",
            "insuredPrice": "785",
            "insured.birthday":"",
            "templateType": "1",
            "employee_id":"",
            "channel":"",
            "empNo":"",
            "newsCode":"",
            "twoMonthInsuredPrice": "1570.00",
            "loginUserId":"",
            "insured.age": dt["year"],
            "insured.sex": "1" if dt["gender"] == "M" else "2",
            "policy.amount": "05" if dt["money"] == "50000" else str(int(dt["money"])/10000),
            "policy.dateRemark":"",
            "person.mobilenum": "承保短信将发送至您的手机"
        }


        payload = urlencode(data).replace("+","")

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and '计算保费成功' in r.text:

            price = Helper.decimalParse( r.json()["totalPremium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

